package com.elife.core;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.googlecode.janrain4j.api.engage.EngageFailureException;
import com.googlecode.janrain4j.api.engage.EngageService;
import com.googlecode.janrain4j.api.engage.ErrorResponeException;
import com.googlecode.janrain4j.api.engage.response.UserDataResponse;
import com.googlecode.janrain4j.api.engage.response.profile.Profile;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	EngageService engageService;
	private String identifier;
	private String providerName;
	private String plainResponse;
	
	@Override
	public String execute() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		final String token = request.getParameter("token");
		
        try {
            UserDataResponse userDataResponse = engageService.authInfo(token, true);
            Profile profile = userDataResponse.getProfile();
            StringBuffer buffer = new StringBuffer();
            buffer.append(profile.getDisplayName()).append(profile.getEmail()).append(profile.getGender()).append(profile.getIdentifier())
            .append(profile.getPhoneNumber()).append(profile.getPhoto()).append(profile.getPreferredUsername()).append(profile.getPrimaryKey())
            .append(profile.getUrl()).append(profile.getVerifiedEmail()).append(profile.getBirthday());
            
			setIdentifier(buffer.toString());
            setProviderName(profile.getProviderName());
            setPlainResponse(userDataResponse.getResponseAsJSON());
            
        }
        catch (EngageFailureException e) {
        	request.setAttribute("error", e);
        	System.out.println("EngageFailureException:" + e);
            //getServletContext().getRequestDispatcher("/error.jsp").forward(req, resp);
        }
        catch (ErrorResponeException e) {
        	request.setAttribute("error", e);
        	System.out.println("ErrorResponeException:" + e);
            //getServletContext().getRequestDispatcher("/error.jsp").forward(req, resp);
        }
		
		return SUCCESS;
	}

	
	
	
	public String getIdentifier() {
		return identifier;
	}




	public void setIdentifier(String identifier) {
		this.identifier = identifier;
	}




	public String getProviderName() {
		return providerName;
	}




	public void setProviderName(String providerName) {
		this.providerName = providerName;
	}




	public String getPlainResponse() {
		return plainResponse;
	}




	public void setPlainResponse(String plainResponse) {
		this.plainResponse = plainResponse;
	}




	public EngageService getEngageService() {
		return engageService;
	}

	public void setEngageService(EngageService engageService) {
		this.engageService = engageService;
	}
	
}
